// pages/test/vip/index.js
const {
  pay,
  payMember,
  couponUseList,
  vipPriceList
} = require('../../../api/api')
const {
  viluntarySmartAdd,
} = require('../../../api/ai')
const {checkLogin} = require("../../../utils/util");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgList: [
      'https://ehsimg.oss-cn-beijing.aliyuncs.com/temp/5e308f39b69342a5bf63d835899bf8b1.jpg',
      'https://ehsimg.oss-cn-beijing.aliyuncs.com/temp/5b6836a38dd1476289f980a89d7a8b4d.jpg',
      'https://ehsimg.oss-cn-beijing.aliyuncs.com/temp/615061f4a92e4077baf1c5c187d5fc20.jpg',
      'https://ehsimg.oss-cn-beijing.aliyuncs.com/temp/bea42e781ef54e93b5e83ff58f201174.jpg',
      'https://ehsimg.oss-cn-beijing.aliyuncs.com/temp/411ab04df54a43ceaeaacaa6078c7eea.jpg',
    ],
    mode: 'vip',
    show: false,
    navHeight: getApp().globalData.navHeight,
    navTop: getApp().globalData.navTop,
    menuHeight: getApp().globalData.menuHeight,
    loginVisible: true,
    status: 20,
    windowHeight: getApp().globalData.windowHeight,
    bottomLift: getApp().globalData.bottomLift,
    list: [],
    visible: false,
    title: '可用优惠券',
    content: '你有一张优惠券可用',
    couponList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.params) {
      const params = JSON.parse(decodeURIComponent(options.params))
      if (params.id) {
        this.setData({
          details: params
        })
        wx.setNavigationBarTitle({
          title: params.title,
        })
      } else {
        this.setData({
          ...params,
          newObj: params
        })
      }
    }
    this.fetchUserInfo()
    this.getList()
  },
  async getList() {
    const {
      result
    } = await vipPriceList()
    const vipList = result.filter((item) => {
      return item.title == 'vip'
    })
    const svipList = result.filter((item) => {
      return item.title == 'svip'
    })
    var gapPrice = svipList[0].netPrice - vipList[0].netPrice
    this.setData({
      vipObj: vipList[0],
      svipObj: svipList[0],
      gapPrice
    })

  },
  async fetchUserInfo() {
    const userInfo = await getApp().fetchUserInfo()
    this.setData({
      mode: userInfo.vipType
    })
  },
  onPageScroll(e) {},
  back() {
    wx.navigateBack()
  },
  confirm(e) {
    const couponId = e.detail
    const {
      vipType
    } = this.data
    if (this.data.newObj) {
      this.doWxPay(vipType, couponId)
    } else {
      this.doWxPayNoNewObj(vipType, couponId)
    }
  },

  async pay(e) {
    checkLogin().then(async res=>{
      const {
        type,
        price
      } = e.currentTarget.dataset
      this.setData({
        vipType: type,
        vipPrice: price
      })
      // if (!wx.getStorageSync('subjectInfo')) {
      //   this.setData({
      //     show: true
      //   })
      //   return
      // }
      const {
        result
      } = await couponUseList(price)
      if (result.length > 0) {
        this.setData({
          visible: true,
          couponList: result,
          content: '您有' + result.length + '张优惠券可用',
          vipType: type
        })
      } else {
        if (this.data.newObj) {
          this.doWxPay(type)
        } else {
          this.doWxPayNoNewObj(type)
        }
      }
    }).catch(e=>{
      wx.navigateTo({
        url: '/pages/login/index',
      })
    })
  },
  async update() {
    const {
      vipType,
      vipPrice
    } = this.data
    const {
      result
    } = await couponUseList(vipPrice)
    if (result.length > 0) {
      this.setData({
        visible: true,
        couponList: result,
        content: '您有' + result.length + '张优惠券可用',
      })
    } else {
      if (this.data.newObj) {
        this.doWxPay(vipType)
      } else {
        this.doWxPayNoNewObj(vipType)
      }
    }
  },
  async doWxPay(type, couponId) {
    const {
      provinceId,
      province,
      score,
      ranking,
      firstSelect,
      secondSelect,
      year
    } = this.data
    const params = {
      provinceId,
      province,
      score,
      ranking,
      firstSelect,
      secondSelect,
      vipType: type,
      year
    }
    if (couponId) {
      params.couponId = couponId
    }
    const {
      result
    } = await payMember(params)
    const _this = this
    wx.requestPayment({
      nonceStr: result.nonceStr,
      package: result.package,
      paySign: result.paySign,
      timeStamp: result.timeStamp,
      signType: result.signType,
      success: async function (res) {
        wx.showToast({
          icon: 'success',
          title: '支付完成',
        })
        _this.message()

      },
      fail: function (res) {}
    })
  },
  async doWxPayNoNewObj(type, couponId) {
    const {
      score,
      ranking,
      year,
      firstSelectSubjects,
      secondSelectSubjects,
      provinceId,
      province
    } = wx.getStorageSync('subjectInfo')
    const params = {
      provinceId,
      province,
      score,
      ranking,
      firstSelect: firstSelectSubjects,
      secondSelect: secondSelectSubjects,
      year,
      vipType: type
    }
    if (couponId) {
      params.couponId = couponId
    }
    const {
      result
    } = await payMember(params)
    const _this = this
    wx.requestPayment({
      nonceStr: result.nonceStr,
      package: result.package,
      paySign: result.paySign,
      timeStamp: result.timeStamp,
      signType: result.signType,
      success: async function (res) {
        wx.showToast({
          icon: 'success',
          title: '支付完成',
        })
        getApp().fetchUserInfo()
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 300);
      },
      fail: function (res) {

      }
    })
  },
  async message() {
    const newObj = this.data
    wx.showToast({
      icon: 'success',
      title: '会员开通成功',
    })
    // const userInfo = await getApp().fetchUserInfo()
    // var {
    //   result
    // } = await viluntarySmartAdd(newObj)
    // if (result) {
    //   result.level1Name = result.localBatchName == '本科批' ? '本科' : '专科（高职）'
    wx.redirectTo({
      url: '/pages/volunteer/loading/index?params=' + encodeURIComponent(JSON.stringify(newObj)),
    })
    // }

  },
})
